package com.edu.neusoft.student.controller;

import com.edu.neusoft.student.domain.Salesrecord;
import com.edu.neusoft.student.service.SalesrecordService;
import com.edu.neusoft.student.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/salesrecords")
@Api(tags = "Salesrecord Management API", description = "Operations related to sales record management")
@Validated
public class SalesrecordController {

    @Autowired
    private SalesrecordService salesrecordService;

    // 根据ID获取销售记录
    @GetMapping("/{salesrecordid}")
    @ApiOperation(value = "Get sales record by ID", notes = "Retrieve a sales record by its ID")
    public AjaxResult getSalesrecordById(@PathVariable Integer salesrecordid) {
        Salesrecord salesrecord = salesrecordService.selectByPrimaryKey(salesrecordid);
        if (salesrecord != null) {
            return AjaxResult.success("Sales record retrieved successfully", salesrecord);
        } else {
            return AjaxResult.error("Sales record not found");
        }
    }

    // 添加新的销售记录
    @PostMapping
    @ApiOperation(value = "Add new sales record", notes = "Create a new sales record in the system")
    public AjaxResult addSalesrecord(@Valid @RequestBody Salesrecord salesrecord) {
        int result = salesrecordService.insert(salesrecord);
        if (result > 0) {
            return AjaxResult.success("Sales record added successfully");
        } else {
            return AjaxResult.error("Failed to add sales record");
        }
    }

    // 更新销售记录
    @PutMapping("/{salesrecordid}")
    @ApiOperation(value = "Update sales record", notes = "Update an existing sales record by its ID")
    public AjaxResult updateSalesrecord(@PathVariable Integer salesrecordid, @Valid @RequestBody Salesrecord salesrecord) {
        salesrecord.setSalesrecordid(salesrecordid); // 设置更新的ID
        int result = salesrecordService.updateByPrimaryKey(salesrecord);
        if (result > 0) {
            return AjaxResult.success("Sales record updated successfully");
        } else {
            return AjaxResult.error("Failed to update sales record");
        }
    }

    // 删除销售记录
    @DeleteMapping("/{salesrecordid}")
    @ApiOperation(value = "Delete sales record", notes = "Delete a sales record by its ID")
    public AjaxResult deleteSalesrecord(@PathVariable Integer salesrecordid) {
        int result = salesrecordService.deleteByPrimaryKey(salesrecordid);
        if (result > 0) {
            return AjaxResult.success("Sales record deleted successfully");
        } else {
            return AjaxResult.error("Failed to delete sales record");
        }
    }
}
